<template>
  <div>
    <a-alert v-if="form.orderSource == 2" type="info" class="mb-2">
      <div>
        通过代客下单创建渠道订单，后续不会根据渠道平台订单的变化而更新，需自行在启程系统进行全流程的手动维护，请在启程系统及时操作排车，防止超卖！
      </div>
    </a-alert>
    <page-form-row>
      <page-form-item :disabled="disabled || mode == 'editOrder'" field="orderSource" label="订单来源">
        <a-select placeholder="请选择" v-model="form.orderSource" @change="changeOrderSourceFn">
          <a-option v-for="item in dict.orderSourceEnum" :key="item.value" :label="item.label" :value="item.value" />
        </a-select>
      </page-form-item>
      <page-form-item :disabled="disabled || mode == 'editOrder'" field="channelType" label="订单渠道">
        <sysdict-select
          :disabled="form.orderSource == 1"
          v-model="form.channelType"
          allow-clear
          :disabledList="channelOrderDisableList"
          code="short_order_channel_type"
          @change="changeOrderChannelFn"
        />
      </page-form-item>
      <page-form-item
        :disabled="time_range_disabled && !isTiexing"
        field="timeRange"
        label="预计租赁周期"
        labelTooltipContent="租赁周期最小时间范围为1小时"
      >
        <template #label-extra>
          <div class="rent-days"> 租期：{{ form.rentDays || '- 天' }} </div>
        </template>
        <i-separate-range-picker
          class="w-full separate-range-picker"
          show-time
          v-model="form.timeRange"
          startPlaceHolder="开始时间"
          endPlaceHolder="结束时间"
          format="YYYY-MM-DD HH:mm"
          valueFormat="YYYY-MM-DD HH:mm:00"
          :time-picker-props="{
            format: 'HH:mm',
            hideDisabledOptions: true,
          }"
          @change="changeTimeRange"
          position="br"
        />
        <template #extra>
          <div class="arco-form-item-message" v-if="orderInfo?.reletFlag == 1">
            订单有续租，为保证数据及金额准确，请先删除续租，再修改预计租赁周期
          </div>
        </template>
      </page-form-item>
      <page-form-item field="orderAcquisitionType" label="订单获取方式">
        <sysdict-select
          v-model="form.orderAcquisitionType"
          allow-clear
          allow-search
          code="short_order_acquisition_type"
          @change="changeOrderAcquisitionTypeFn"
        />
      </page-form-item>
      <page-form-item :disabled="disabled || mode == 'editOrder'" field="channelOrderCode" label="渠道单号" v-if="form.orderSource == 2">
        <i-input v-model="form.channelOrderCode" :max-length="32" />
      </page-form-item>
    </page-form-row>
    <page-form-row>
      <page-form-item :disabled="disabled && !isTiexing" field="siteId" label="取车门店">
        <template #label-extra>
          <a-checkbox v-model="form.sendServiceFlag" :disabled="sendServiceFlagDisabled" @change.stop>上门送车</a-checkbox>
        </template>
        <remote-select
          v-model="form.siteId"
          :params="{ oldId: form.siteId, siteStatusList: [10] }"
          type="site_listBystaff"
          :allow-clear="false"
          @change="(val) => changeSiteIdFn(val, 'site')"
        />
      </page-form-item>
      <page-form-item :disabled="(orderStatus == 'orderCompleted' || !orderIsMaintenance(orderInfo)) && !isTiexing" label="还车门店">
        <template #label-extra>
          <a-checkbox v-model="form.returnServiceFlag" :disabled="returnServiceFlagDisabled">上门取车</a-checkbox>
        </template>
        <remote-select
          v-model="form.returnSiteId"
          :params="{ siteType: 40, siteId: form.siteId, siteStatusList: [10] }"
          type="site_lease_list"
          :allow-clear="false"
          @change="(val) => changeSiteIdFn(val, 'returnSite')"
          @listGet="returnSiteListGetFn"
        />
      </page-form-item>
      <page-form-item
        :disabled="disabled && !isTiexing"
        field="originalModelId"
        label="车型"
        labelTooltipContent="请先选择租赁周期和取车门店后，再选择车型"
      >
        <select-input
          :disable="(disabled || !form.rentDays || !form.siteId) && !isTiexing"
          v-model="form.originalModelName"
          @clear="clearCarModelFn"
          @click="selectCarModelFn"
        />
      </page-form-item>
      <page-form-item :disabled="disabled" field="address" label="上门送车地址">
        <template #label-extra>
          <div class="map-location" :class="[!form.sendServiceFlag ? 'disabled' : '']" @click="mapLocationClickFn('address')">
            <icon-location /> 地图选择
          </div>
        </template>
        <lease-auto-complete
          :disabled="!form.sendServiceFlag"
          v-model="form.address"
          @change="(point) => autoCompleteChangeFn(point, 'address')"
          @blur="updateLnglatPickerTips('address')"
        />
      </page-form-item>
      <page-form-item
        :disabled="orderStatus == 'orderCompleted' || !orderIsMaintenance(orderInfo)"
        field="returnAddress"
        label="上门取车地址"
      >
        <template #label-extra>
          <div class="map-location" :class="[!form.returnServiceFlag ? 'disabled' : '']" @click="mapLocationClickFn('returnAddress')">
            <icon-location /> 地图选择
          </div>
        </template>
        <lease-auto-complete
          :disabled="!form.returnServiceFlag"
          v-model="form.returnAddress"
          @change="(point) => autoCompleteChangeFn(point, 'returnAddress')"
          @blur="updateLnglatPickerTips('returnAddress')"
        />
      </page-form-item>
      <page-form-item label="订单备注" size="2/3" class="mb-0">
        <i-textarea v-model="form.remark" />
      </page-form-item>
    </page-form-row>

    <!-- 坐标选择 -->
    <lnglat-picker-modal title="地图选择" ref="lnglatPickerModalRef" @change="mapLocationSuccessFn" />
    <!-- 车型选择 -->
    <car-model-selector ref="carModelSelectorRef" @confirm="carModelConfirmFn" />
  </div>
</template>
<script setup>
  import { ref, inject, computed, nextTick, watchEffect } from 'vue'
  import { getSiteLeaseDetail } from '@/api/asset/site'
  import { computeRentDay } from '@/api/order/sOrder'
  import carModelSelector from '@/views/assets/car/stock/car-model-selector.vue'
  import leaseAutoComplete from './lease-auto-complete.vue'
  import iTextarea from '@/views/order/short-order/components/i-textarea.vue'
  import selectInput from './select-input.vue'
  import { Modal, Message } from '@arco-design/web-vue'
  import { orderIsMaintenance } from '../../utils.js'
  import useUserStore from '@/store/modules/user'

  // 列表页，修改承租人信息时 isListEditMember 传为 true
  const props = defineProps({
    // 场景
    mode: {
      type: String,
      default: 'createOrder', // editLesseeMemberModal （编辑承租人弹窗）| createOrder（创建订单）| editOrder（编辑订单）
    },
    orderStatus: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    isTiexing: {
      type: Boolean,
      default: false,
    },
  })
  const emits = defineEmits(['timeRangeChange'])

  const userStore = useUserStore()
  console.log('userStore', userStore.enterpriseDetail)
  const orderInfo = inject('orderInfo')

  const time_range_disabled = ref(true)
  // watchEffect 自动监听响应式属性
  watchEffect(() => {
    console.log('orderInfo', orderInfo)
    if (orderInfo && orderInfo.value) {
      // channelOrderMaintenance 1：自动维护 2：手动维护
      // orderStatus 200: 用车中 300: 已还车 1000: 已完成
      // reletFlag 是否续租(0:否 1:是)
      const isMaintenance =
        orderInfo.value.orderSource == 1 || (orderInfo.value.orderSource == 2 && orderInfo.value.channelOrderMaintenance == 2)
      const isCompleted = props.orderStatus == 'orderInProgress' || props.orderStatus == 'orderCompleted'
      const isRelet = orderInfo.value.reletFlag == 1

      if (props.orderStatus == 'notStarted') {
        time_range_disabled.value = props.disabled
      } else {
        if (isMaintenance && isCompleted && !isRelet) {
          time_range_disabled.value = false
        } else {
          time_range_disabled.value = true
        }
      }
    } else {
      time_range_disabled.value = props.disabled
    }
  })

  const channelOrderDisableList = computed(() => {
    // return userStore.enterpriseDetail.channelOrderMaintenance == 1 ? [-3] : []
    // 6.0.13 不在禁用铁行渠道
    return []
  })
  const form = inject('form')
  const formRef = inject('formRef')
  const formDisabled = inject('formDisabled')
  const dict = inject('dict')
  const changeTimeRange = (value = []) => {
    form.value.startTime = value[0]
    form.value.endTime = value[1]
    if (value[0] && value[1]) {
      // 计算租期
      const param = {
        startTime: value[0],
        endTime: value[1],
        siteId: form.value.siteId,
      }
      computeRentDay(param).then((res) => {
        let { days } = res.result
        if (days.indexOf('小时') >= 0 && days.indexOf('天') >= 0) {
          days = days.replace('天', ' 天 ').replace('小时', ' 小时')
        } else {
          days = days.replace('天', ' 天').replace('小时', ' 小时')
        }
        form.value.rentDays = days
        emits('timeRangeChange', value)
      })
    } else {
      form.value.rentDays = undefined
    }
  }
  // 切换订单来源
  const changeOrderSourceFn = () => {
    form.value.channelType = undefined
    form.value.channelOrderCode = undefined
  }
  // 切换订单渠道
  const changeOrderChannelFn = () => {
    form.value.channelOrderCode = undefined
  }
  const changeOrderAcquisitionTypeFn = (a, option) => {
    if (option) {
      form.value.orderAcquisitionName = option
    } else {
      form.value.orderAcquisitionName = ''
    }
  }
  // 地图选点
  const lnglatPickerModalRef = ref()
  const lnglatPickerType = ref('')
  const mapLocationClickFn = (type) => {
    if (formDisabled) return
    if ((type == 'address' && form.value.sendServiceFlag) || (type == 'returnAddress' && form.value.returnServiceFlag)) {
      lnglatPickerType.value = type
      let lnglat = []
      if (type == 'address') {
        if (form.value.longitude && form.value.latitude) lnglat = [form.value.longitude, form.value.latitude]
      } else {
        if (form.value.returnLongitude && form.value.returnLatitude) lnglat = [form.value.returnLongitude, form.value.returnLatitude]
      }
      if (lnglat.length > 0) {
        lnglatPickerModalRef.value.open(lnglat.join(','))
      } else {
        lnglatPickerModalRef.value.open()
      }
    }
  }
  // 地图选点结束
  const mapLocationSuccessFn = (lnglat, option) => {
    if (lnglatPickerType.value == 'address') {
      form.value.longitude = lnglat[0]
      form.value.latitude = lnglat[1]
      form.value.address = option.formattedAddress
    } else {
      form.value.returnLongitude = lnglat[0]
      form.value.returnLatitude = lnglat[1]
      form.value.returnAddress = option.formattedAddress
    }
    // 更新 field 提示
    updateLnglatPickerTips(lnglatPickerType.value)
  }
  // 地点输入回调
  const autoCompleteChangeFn = (lnglat, type) => {
    if (!lnglat) {
      if (type == 'address') {
        form.value.longitude = undefined
        form.value.latitude = undefined
      } else {
        form.value.returnLongitude = undefined
        form.value.returnLatitude = undefined
      }
    } else {
      if (type == 'address') {
        form.value.longitude = lnglat[0]
        form.value.latitude = lnglat[1]
      } else {
        form.value.returnLongitude = lnglat[0]
        form.value.returnLatitude = lnglat[1]
      }
      // 更新 field 提示
      updateLnglatPickerTips(type)
    }
  }
  // 更新地址提示
  const updateLnglatPickerTips = (type) => {
    let formVal = form.value
    let longitudeProp = ''
    let latitudeProp = ''
    if (type == 'address') {
      longitudeProp = 'longitude'
      latitudeProp = 'latitude'
    }
    if (type == 'returnAddress') {
      longitudeProp = 'returnLongitude'
      latitudeProp = 'returnLatitude'
    }
    if (formVal[longitudeProp] && formVal[latitudeProp]) {
      formRef.value.clearValidate(type)
    } else {
      formRef.value.setFields({
        [`${type}`]: {
          status: 'error',
          message: '当前位置无法定位，将会影响费用计算。请选择具体取车地址或地图中选取地址',
        },
      })
    }
  }
  // 选择车型
  const carModelSelectorRef = ref()
  const selectCarModelFn = () => {
    if ((props.disabled || formDisabled) && !props.isTiexing) return
    if (form.value.rentDays && form.value.siteId) {
      const param = {
        siteId: form.value.siteId,
        modelId: form.value.originalModelId,
        // 默认7天
        dateRange: form.value.timeRange,
      }
      console.log(param)
      carModelSelectorRef.value.open(param)
    } else {
      Message.error('请先选择租赁周期和取车门店后，再选择车型')
    }
  }
  // 车型选择完成
  const carModelConfirmFn = (id, option) => {
    form.value.originalModelId = id
    form.value.originalModelName = option.modelName

    // 判断当前排车车型是否和当前车型一致，符合则无变化，不符合则车牌号清空
    if (form.value.carModelId && form.value.carModelId !== id) {
      // 清空车辆信息
      form.value.carId = undefined
      form.value.carLicenseNo = undefined
      form.value.carModelId = undefined
      form.value.carModelName = undefined
    }

    // 去除校验文本
    formRef.value.clearValidate('originalModelId')
  }
  // 清空车型
  const clearCarModelFn = () => {
    form.value.originalModelId = undefined
    form.value.originalModelName = undefined
  }

  // 取车门店短租配置
  const siteShortSiteConfig = ref({})
  // 还车门店短租配置
  const returnSiteShortSiteConfig = ref({})
  // 上门送车开关是否可选
  const sendServiceFlagDisabled = computed(() => {
    return !siteShortSiteConfig.value.isOnsiteService
  })
  // 上门取车开关是否可选
  const returnServiceFlagDisabled = computed(() => {
    return !returnSiteShortSiteConfig.value.isOnsiteService
  })
  // 清空 address 相关值
  const clearAddress = (type = 'address') => {
    formRef.value.clearValidate(type)
    if (type == 'address') {
      form.value.sendServiceFlag = false
      form.value.address = undefined
      form.value.longitude = undefined
      form.value.latitude = undefined
    } else {
      form.value.returnServiceFlag = false
      form.value.returnAddress = undefined
      form.value.returnLongitude = undefined
      form.value.returnLatitude = undefined
    }
  }
  // 切换门店
  const prevSiteId = ref()
  const changeSiteIdFn = (val, type) => {
    new Promise((resolve) => {
      if (props.mode == 'editOrder' && type == 'site') {
        // 编辑订单，修改取车门店
        Modal.confirm({
          title: '确认',
          content: '变更取车门店，系统将重置车型和车牌号，请确认是否修改？',
          okText: '确认',
          cancelText: '关闭',
          onCancel: () => {
            if (prevSiteId.value) {
              form.value.siteId = prevSiteId.value
            } else {
              form.value.siteId = orderInfo.value.siteId
            }
          },
          onOk: () => {
            prevSiteId.value = val
            resolve()
          },
        })
      } else {
        resolve()
      }
    }).then(() => {
      if (type == 'site') {
        // 切换取车门店，需要清空车型和车牌
        form.value.originalModelId = undefined
        form.value.originalModelName = undefined
        form.value.carId = undefined
        form.value.carLicenseNo = undefined
        form.value.carModelId = undefined
        form.value.carModelName = undefined
      }
      getSiteShortConfig(val, (shortSiteConfig) => {
        type == 'site' ? (siteShortSiteConfig.value = shortSiteConfig) : (returnSiteShortSiteConfig.value = shortSiteConfig)
        nextTick(() => {
          if (type == 'site') {
            // 当前选中
            if (form.value.sendServiceFlag && sendServiceFlagDisabled.value) {
              clearAddress('address')
            }
          } else {
            if (form.value.returnServiceFlag && returnServiceFlagDisabled.value) {
              clearAddress('returnAddress')
            }
          }
        })
      })
    })
  }
  // 读取门店租赁配置
  const getSiteShortConfig = (id, callback) => {
    // 获取门店租赁配置详情
    getSiteLeaseDetail({ id }).then(({ result }) => {
      let config = result.shortSiteConfig || {}
      callback(config)
    })
  }
  // 还车门店列表获取
  const returnSiteListGetFn = (list) => {
    if (list.length > 0) {
      if (!list.find((site) => site.id == form.value.returnSiteId)) {
        clearReturnSite()
      }
    } else {
      clearReturnSite()
    }
  }
  // 清空还车门店相关配置
  const clearReturnSite = () => {
    form.value.returnSiteId = undefined
    form.value.returnSiteName = undefined
    form.value.returnServiceFlag = false
    form.value.returnAddress = undefined
    form.value.returnLongitude = undefined
    form.value.returnLatitude = undefined

    returnSiteShortSiteConfig.value = {}
    formRef.value.clearValidate('returnAddress')
  }
  // 编辑场景下，更新 ShortsiteConfig
  const updateShortsiteConfig = (siteId, typeList) => {
    let formValue = form.value
    // 上门取送车开关默认值
    for (var i = 0; i < typeList.length; i++) {
      let type = typeList[i]
      if (type == 'site') {
        if (formValue.sendServiceFlag) {
          siteShortSiteConfig.value = { isOnsiteService: true }
          typeList.splice(i, 1)
          i--
        }
      } else {
        if (formValue.returnServiceFlag) {
          returnSiteShortSiteConfig.value = { isOnsiteService: true }
          typeList.splice(i, 1)
          i--
        }
      }
    }
    if (typeList.length > 0) {
      // 获取门店租赁配置详情
      getSiteShortConfig(siteId, (shortSiteConfig) => {
        // 父组件读取短租配置后
        typeList.forEach((type) => {
          if (type == 'site') {
            siteShortSiteConfig.value = shortSiteConfig
          } else {
            returnSiteShortSiteConfig.value = shortSiteConfig
          }
        })
      })
    }
  }
  defineExpose({
    updateShortsiteConfig,
    updateLnglatPickerTips,
  })
</script>
<style lang="less" scoped>
  .rent-days {
    color: rgb(var(--primary-6));
  }
  .map-location {
    color: rgb(var(--primary-6));
    font-size: 14px;
    cursor: pointer;
    svg {
      color: rgb(var(--primary-6));
    }
  }
  .map-location.disabled {
    cursor: no-drop;
    color: rgba(24, 144, 255, 0.5);
    svg {
      color: rgba(24, 144, 255, 0.5);
    }
  }
</style>
